<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="addpermission('0',1)">添加权限</el-button>
        </div>

        <el-table border :data="permissionList" row-key="id">
          <el-table-column prop="name" label="名称" />
          <el-table-column prop="code" label="标识" />
          <el-table-column prop="description" label="描述" />
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button v-if="scope.row.type===1" type="text" @click="addpermission(scope.row.id,2)">添加</el-button>
              <el-button type="text" @click="editpermission(scope.row.id)">编辑</el-button>
              <el-button type="text" @click="delpermission(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <!-- 放置一个弹层 用来编辑新增节点 -->
      <el-dialog
        :title="isEdit?'编辑权限点':'新增权限点'"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible="showDialog"
        @close="btnCancel"
      >
        <!-- 表单 -->
        <el-form ref="perForm" :model="formData" :rules="rules" label-width="120px">
          <el-form-item label="权限名称" prop="name">
            <el-input v-model="formData.name" style="width:90%" />
          </el-form-item>
          <el-form-item label="权限标识" prop="code">
            <el-input v-model="formData.code" style="width:90%" />
          </el-form-item>
          <el-form-item label="权限描述">
            <el-input v-model="formData.description" style="width:90%" />
          </el-form-item>
          <el-form-item label="开启">
            <!-- ele的switch -->
            <el-switch
              v-model="formData.enVisible"
              active-value="1"
              inactive-value="0"
            />
          </el-form-item>
        </el-form>
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" type="primary" @click="addPermissionSubmit">确定</el-button>
            <el-button size="small" @click="btnCancel">取消</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { datatotree } from '@/utils'// 将数据转化成树状
import { getPermissionList, addPermission, getPermissionDetail, updatePermission, delPermission } from '@/api/permission'// updatePermission
export default {
  name: 'Permission',
  data() {
    // 同级不能出现重复
    const validName = (rule, value, callback) => {
      // 添加状态的时候
      // 筛选出同级的,然后判断有没有一样的
      let existNameList = this.originList.filter(item => item.pid === this.formData.pid)
      if (this.isEdit) {
        // 编辑状态的时候
        // 需要把自身排除
        existNameList = this.originList.filter(item => item.pid === this.formData.pid && item.id !== this.formData.id)
      }
      existNameList.map(item => item.name).includes(value) ? callback(new Error('权限名称重复')) : callback()
    }
    // 整个权限架构不能出现重复
    const validCode = (rule, value, callback) => {
      // 添加状态的时候
      let existCodeList = this.originList
      if (this.isEdit) {
        existCodeList = this.originList.filter(item => item.id !== this.formData.id)
      }
      // 编辑状态的时候
      existCodeList.map(item => item.code).includes(value) ? callback(new Error('标识重复')) : callback()
    }
    return {
      permissionList: [],
      showDialog: false, // 弹框显示隐藏
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      rules: {

        name: [{ required: true, message: '权限名称不能为空', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }],
        code: [{ required: true, message: '权限标识不能为空', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }]

      },
      isEdit: false,
      originList: []
    }
  },
  created() {
    // 获取权限列表
    this.getPermissionList()
  },
  methods: {
    // 添加权限
    addpermission(pid, type) {
      this.isEdit = false
      this.showDialog = true
      this.formData.pid = pid
      this.formData.type = type
    },
    // 编辑角色
    async editpermission(id) {
      this.isEdit = true
      this.showDialog = true
      // 数据回填
      const res = await getPermissionDetail(id)
      this.formData = res.data
      this.formData.id = id
    },
    // 删除角色
    async delpermission(id) {
      const res = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      console.log(res)
      if (res === 'cancel') return this.$message('已取消删除')
      // 点击确定删除
      const res1 = await delPermission(id)

      // 通知用户
      this.$message.success(res1.message)
      // 重新调取页面权限列表
      this.getPermissionList()
    },
    // 获取所有权限列表
    async getPermissionList() {
      const res = await getPermissionList()
      // 简化数据
      this.originList = res.data.map(({ name, id, pid, code }) => ({ name, id, pid, code }))
      // 将数据处理成树形数据

      this.permissionList = datatotree(res.data, '0')
    },
    // 点击取消关闭
    btnCancel() {
      this.formData = {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      }
      this.$refs.perForm.resetFields()// 重置表单验证
      this.showDialog = false
    },
    // 点击确定
    addPermissionSubmit() {
      this.$refs.perForm.validate(async vali => {
        if (!vali) return

        if (!this.isEdit) {
          const res = await addPermission(this.formData)
          this.$message.success(res.message)
        } else {
          const res = await updatePermission(this.formData)
          this.$message.success(res.message)
        }
        this.isEdit = false// 将状态调回到添加状态
        this.showDialog = false
        this.getPermissionList()
      })
    }

  }
}
</script>

<style lang="scss" scoped></style>
